package com.aube;

import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;

import com.aube.push.PushPhoneModel;
import com.aube.push.PushSetting;
import com.huyn.baseframework.net.OpenApi;
import com.huyn.baseframework.share.ShareUtil;
import com.huyn.baseframework.utils.AppUtil;
import com.huyn.baseframework.utils.Constant;
import com.huyn.baseframework.utils.SharedPrefUtil;
import com.huyn.baseframework.utils.StorageUtil;
import com.huyn.baseframework.utils.StringUtils;
import com.huyn.baseframework.utils.UserUtil;
import com.mcxiaoke.packer.helper.PackerNg;
import com.umeng.analytics.MobclickAgent;
import com.xiaomi.channel.commonutils.logger.LoggerInterface;
import com.xiaomi.mipush.sdk.Logger;

import cn.jpush.android.api.JPushInterface;

/**
 * Created by huyaonan on 16/4/29.
 */
public class AubeApplication extends Application {

    protected static final String TAG = "AubeApplication";

    @Override
    public void onCreate() {
        super.onCreate();

        StaticApplicationContext.init(this);

        if (getApplicationInfo().packageName.equals(getCurProcessName(getApplicationContext()))) {
            StorageUtil.initDiskCacheDir(this);
            initAppArgs();

            UserUtil.restoreIntance(this);

            //发送策略
            //MobclickAgent.updateOnlineConfig(getApplicationContext());
            //禁止默认的页面统计方式，这样将不会再自动统计Activity
            MobclickAgent.openActivityDurationTrack(false);

            if(Constant.DEBUG) {
                String apiPath = SharedPrefUtil.getInstance(this).getString(SharedPrefUtil.API_PATH);
                if (StringUtils.isNotBlank(apiPath))
                    OpenApi.setRouter(apiPath);
            }

            ShareUtil.initContext(this);

            if(PushPhoneModel.getInstance(this).isXiaomi()) {
                registMiPush();
                disableJPush();
            } else {
                enableJPush();
            }

//            LeakCanary.install(this);
        }
    }

    /**
     * 获得当前进程的名字
     * @param context
     * @return 进程号
     */
    public static String getCurProcessName(Context context) {

        int pid = android.os.Process.myPid();

        ActivityManager activityManager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);

        for (ActivityManager.RunningAppProcessInfo appProcess : activityManager
                .getRunningAppProcesses()) {

            if (appProcess.pid == pid) {
                return appProcess.processName;
            }
        }
        return null;
    }

    private void initAppArgs() {
        try {
            Constant.APP_MOBILETYPE = Build.MODEL;
            Constant.APP_DEVICEID = AppUtil.getDeviceId(this);
            // 如果没有使用PackerNg打包添加渠道，默认返回的是""
            // com.mcxiaoke.packer.helper.PackerNg
            final String market = PackerNg.getMarket(this, "default");
            // 或者使用 PackerNg.getMarket(Context,defaultValue)
            // 之后就可以使用了，比如友盟可以这样设置
            MobclickAgent.startWithConfigure(new MobclickAgent.UMAnalyticsConfig(this, getString(R.string.umeng_key), market));

            Constant.APP_SOURCE = market;

            PackageManager manager = this.getPackageManager();
            PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0);
            Constant.APP_VERSION = info.versionName;

            //会因为权限问题导致异常,放在最后处理,以防影响其它的值的获取
            Constant.APP_IMEI = AppUtil.getIMEI(this);// 获取IMEI号
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void registMiPush(){}

    public void registMiPush(String id, String key) {
        StaticApplicationContext.MI_PUSH_ID = id;
        StaticApplicationContext.MI_PUSH_KEY = key;
        if(PushSetting.isPushOn(this)) {
            PushSetting.registMiPush(this, id, key);
        }

        LoggerInterface newLogger = new LoggerInterface() {

            @Override
            public void setTag(String tag) {
                // ignore
            }

            @Override
            public void log(String content, Throwable t) {
                Log.d(TAG, content, t);
            }

            @Override
            public void log(String content) {
                Log.d(TAG, content);
            }
        };
        Logger.setLogger(this, newLogger);
    }

    public void enableJPush() {}

    public void disableJPush() {}

    public void enableJPush(Context context) {
        if(Constant.DEBUG)
            JPushInterface.setDebugMode(true);
        else
            JPushInterface.setDebugMode(false);

        JPushInterface.init(context); // Init JPush

        if(PushSetting.isPushOn(context)) {
            JPushInterface.resumePush(context);
        } else {
            JPushInterface.stopPush(context);
        }
    }

    public void disableJPush(Context context) {
        if(Constant.DEBUG)
            JPushInterface.setDebugMode(true);
        else
            JPushInterface.setDebugMode(false);

        JPushInterface.init(context); // Init JPush
        JPushInterface.stopPush(context); // no disable api provided by jpush
    }

    public void startActivity(Context context, Bundle bundle) {}

}